package com.servlet;

import com.Imp.CustomerMapperImpl;
import com.Imp.UserMapperImpl;
import com.entity.Customer;
import com.entity.User;
import com.mapper.CustomerMapper;
import com.mapper.UserMapper;
import com.service.CustomerService;
import javax.servlet.ServletException;
import javax.servlet.http.*;
import java.io.IOException;
import java.util.List;

public class CustomerController extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        CustomerService customerService = new CustomerService();
        List<Customer> customers = customerService.getAllCustomers();
        request.setAttribute("customers", customers);
        request.getRequestDispatcher("/WEB-INF/jsp/customer.jsp").forward(request, response);
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");

        HttpSession session = request.getSession();
        String userName = (String) session.getAttribute("username");
        //获取所有登录数据
        String name=(String)request.getParameter("name");
        String gender=(String)request.getParameter("gender");
        String age=(String)request.getParameter("age");
        String phoneNumber=(String)request.getParameter("phoneNumber");
        String address=(String)request.getParameter("address");
        System.out.println("123");
        CustomerMapper customerMapper = new CustomerMapperImpl();
        UserMapper userMapper = new UserMapperImpl();
        User user = userMapper.getUserByUsername(userName);
        Customer customer = customerMapper.getCustomerByUserName(userName);
        if(customer == null){
            customer = new Customer();
            customer.setUserName(userName);
            customer.setName(name);
            customer.setSex(gender);
            customer.setAge(age);
            customer.setPassWord(user.getPassWord());
            customer.setPhone(phoneNumber);
            customer.setAddress(address);
            customerMapper.addCustomer(customer);
            response.sendRedirect("information_customer.jsp");
        }
        else{
            customer.setName(name);
            customer.setSex(gender);
            customer.setAge(age);
            customer.setPhone(phoneNumber);
            customer.setAddress(address);
            //将更改后的信息插入数据库中
            customerMapper.updateCustomer(customer);
            response.sendRedirect("information_customer.jsp");
        }

    }
}
